package com.huidz.calendar.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.transition.Slide;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.huidz.calendar.R;
import com.huidz.calendar.mainfragment.RemindFragment;
import com.huidz.calendar.model.UserModel;
import com.huidz.calendar.util.Apiutils;
import com.huidz.calendar.util.AppManager;
import com.huidz.calendar.util.Url;
import com.huidz.calendar.view.VerificationAction;
import com.huidz.calendar.view.VerificationCodeEditText;

import org.json.JSONObject;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class GetCodeActivity extends AppCompatActivity implements View.OnClickListener {

    private Handler handler = new Handler();
    private Runnable runnable;
    private ImageView comeback;
    private VerificationCodeEditText am_et;

    private TextView codetime, getphonenumtext;

    private int setpost = 0;
    private int tiemid = 60;

    private String getphomenum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Slide slide = new Slide(Gravity.BOTTOM);
        slide.setDuration(200L);//间歇时间
        getWindow().setEnterTransition(slide);
        setContentView(R.layout.activity_getcode);
        inti();
    }

    public int conll = 0;

    /**
     * 初始化加载调用方法
     */
    public void inti() {
        Intent getint = getIntent();
        getphomenum = getint.getStringExtra("phonenum");
        getphonenumtext = findViewById(R.id.getphonenum);
        getphonenumtext.setText("验证码已发送至你手机 +86 " + getphomenum);
        comeback = findViewById(R.id.title_comeback);
        comeback.setOnClickListener(this);
        am_et = findViewById(R.id.am_et);
        am_et.setOnVerificationCodeChangedListener(new VerificationAction.OnVerificationCodeChangedListener() {
            @Override
            public void onVerCodeChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() >= 5) {
                    okHttp_postFromParameters_codelogin(s.toString());
                }
            }

            @Override
            public void onInputCompleted(CharSequence s) {

            }
        });
        codetime = findViewById(R.id.codetime);
        codetime.setOnClickListener(this);
        runnable = new Runnable() {
            public void run() {
                if (tiemid == 0) {
                    StopTime();
                } else {
                    tiemid--;
                    codetime.setText(tiemid + "秒后重新获取验证码");
                    handler.postDelayed(this, 1000);
                }
            }
        };
        handler.postDelayed(runnable, 1000);
        setpost = 1;
        okHttp_postFromParameters();
    }

    public void StopTime() {
        setpost = 0;
        tiemid = 60;
        handler.removeCallbacks(runnable);
        codetime.setText("重新获取验证码");
    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.title_comeback:
                onBackPressed();
                break;

            case R.id.codetime:
                if (setpost == 0) {
                    okHttp_postFromParameters();
                    setpost = 1;
                    handler.postDelayed(runnable, 1000);
                }
                break;
        }
    }

    public void okHttp_postFromParameters() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("mobile", getphomenum)
                            .build();
                    Request request = new Request.Builder().url(Url.GETCODE).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void okHttp_postFromParameters_codelogin(final String code) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    conll++;
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody formBody = new FormBody.Builder().add("mobile", getphomenum).add("code", code)
                            .build();
                    Request request = new Request.Builder().url(Url.CODELOGIN).post(formBody).build();
                    okhttp3.Response response = okHttpClient.newCall(request).execute();
                    String msg = response.body().string();
                    Message message = new Message();
                    message.obj = msg;
                    gethot.sendMessage(message);
                } catch (
                        Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;
    public UserModel userm;
    public Handler gethot = new Handler() {
        public void handleMessage(Message msg) {
            String msgs = null;
            try {
                JSONObject success_Object = null;
                if (msg.obj != null) {
                    success_Object = new JSONObject(msg.obj.toString());
                    String code = success_Object.getString("code");
                    msgs = success_Object.getString("msg");
                    if (code.equals("1")) {
                        Gson gson = new Gson();
                        userm = gson.fromJson(msg.obj.toString(),
                                UserModel.class);
                        mSharedPreferences = getSharedPreferences("user", MODE_PRIVATE);  //名称和类型
                        mEditor = mSharedPreferences.edit();
                        mEditor.putString("user_token", userm.getData().getLogintoken());
                        Url.USER_TOKEN = userm.getData().getLogintoken();
                        mEditor.putString("user_name", userm.getData().getNickname());
                        Url.USER_NAME = userm.getData().getNickname();
                        mEditor.putString("user_mobile", userm.getData().getMobile());
                        Url.USER_MOBILE = userm.getData().getMobile();
                        mEditor.putString("user_head", userm.getData().getAvatar());
                        Url.USER_HEAD = userm.getData().getAvatar();
//                        mEditor.putString("user_phone", userm.getData().getUser_phone());
//                        Url.USER_PHONE_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_wechat", userm.getData().getUser_wechat());
//                        Url.USER_WECHAT_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_wechatpwd", userm.getData().getUser_wechatpwd());
//                        mEditor.putString("user_zfb_zh", userm.getData().getUser_zfb_zh());
//                        Url.USER_ALIPAY_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_zfb_name", userm.getData().getUser_zfb_name());
//                        Url.USER_ALIPAY_USER_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_nickname", userm.getData().getUser_nickname());
//                        Url.USER_NICK_NAME = userm.getData().getUser_name();
//                        mEditor.putString("user_head", userm.getData().getUser_head());
//                        Url.USER_HEAD_IMG = userm.getData().getUser_head();
//                        mEditor.apply();
//                        mEditor.commit();okHttp_postFromParameter();

                        RemindFragment.shuaxing=true;
                        AppManager.getAppManager().finishActivity(User_LoginActivity.class);
                        onBackPressed();
                    } else {
                        Apiutils.SetToast(GetCodeActivity.this, msgs);
                    }
                }
            } catch (
                    Exception e) {
                e.printStackTrace();
            }
        }
    };


}
